/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.edu.pucp.Util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pe.edu.pucp.Modelo.Actividad;
import pe.edu.pucp.Modelo.Log;
import pe.edu.pucp.Modelo.Objeto;
import pe.edu.pucp.Modelo.Usuario;

/**
 *
 * @author jorge
 */
public class LogHelper {
    
    public static void registrarOperacion(Usuario usr,int act,int obj, String desc){
        try {
            Log log = new Log();
            log.setUsuario(usr);
            log.setPerfil(usr.getPerfil());
            log.setFechareg(new Date());
            log.setActividad(buscarAccion(act));
            log.setObjeto(buscarObjeto(obj));
            log.setDescripcion(desc);
            InetAddress ip = InetAddress.getLocalHost();     
            log.setIp(ip.getHostAddress());   
            guardarLog(log);
        } catch (UnknownHostException ex) { }
    }
    
    private static Log guardarLog(Log p){     
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx =  null;
        try{
            tx = session.beginTransaction();
            session.save(p);                                              
            tx.commit();  
        }catch(Exception e) {
            if (tx!=null) tx.rollback();
        } finally {
            session.close();                      
            return p;       
        }
    } 
    
    private static Actividad buscarAccion(int act){
        Actividad a = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();                        
        Query query = session.createQuery("from Actividad where idactividad = :act");
        query.setInteger("act", act);
        List lista = query.list();
        Iterator iter = lista.iterator();
        if (iter.hasNext()) {    
            a = (Actividad) iter.next();                  
        }

        tx.commit();
        session.close();
        return a;
              
    } 
    
    private static Objeto buscarObjeto(int obj){
        Objeto a = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();                        
        Query query = session.createQuery("from Objeto where idobjeto = :obj");
        query.setInteger("obj", obj);
        List lista = query.list();
        Iterator iter = lista.iterator();
        if (iter.hasNext()) {    
            a = (Objeto) iter.next();                  
        }

        tx.commit();
        session.close();
        return a;
              
    }     
}
